#/usr/bin/python
# coding: utf8

import time
import PAM30
import winsound
import sys
import win32api

reload(sys)
sys.setdefaultencoding("utf-8")


def searchWd(sword, itemid, itemname):
    ie.navigate('http://www.taobao.com')
    ie.setTextBox('q', sword)
    ie.submitForm('search')
    #ie.clickButton('搜索')
    time.sleep(2)
    #idstr = 'id='+itemid
    #rt = ie.findText(idstr)
    #print taoid.encode('gbk')
    rt = ie.findText(itemid)
    if(rt):
        #找到淘宝id，然后点击商品链接
        print ("find "+itemname.encode('gbk'))

        #IE8要有个初始化设置，总是允许来自s.taobao.com的弹出窗口
        pdt = ie.findElement('a', 'title', itemname)        
        ie.clickElement(pdt)
        time.sleep(2)
        
        consis = str(pdt).find('tmall')
        if(consis == -1):
            ie.changeWindow(itemname+'-淘宝网')
        else:
            ie.changeWindow(itemname+'-tmall.com天猫')
        
        s1 = '白色1.6米'        
        c1 = ie.findElement('span', 'innerText', s1)
        f = ie.clickElement(c1)
        print f
        #购买
        buy = ie.findElement('div', 'id', 'J_juValid')
        a = ie.getElementChildren(buy)
        b = ie.getElementChildren(a[0])
        eleArry = ie.getElementChildren(buy)
        ie.clickElement(b[0])
        time.sleep(2)
    else:
        i = 0 #只寻找2页
        while(i<10):
            ie.clickLink('下一页')            
            rt = ie.findText(itemid)
            if(rt):
                print 'found it'
                break
            else:
                i = i+1


ie= PAM30.PAMIE()
sword = u'时尚简约双人电脑桌书架组合 家用台式书桌书柜书橱办公桌'
itemid = 'id=15142253094'
itemname = '时尚简约双人电脑桌书架组合 家用台式书桌书柜书橱办公桌'

searchWd(sword, itemid, itemname)
winsound.Beep(370, 200)
